-module(handler_update_usrinfo).
-export([init/3]).
-export([info/3]).
-export([terminate/3]).

-include("common.hrl").

init(_, Req, _Opts) ->
%% 	?debug("---,~p",[Req]),
	Ret = 
		case get_input_data(Req) of
			{ok, ActionInfo, Req3} ->{ok, ActionInfo, Req3};
			_ ->{false, {?RET_INVALID_ARG, <<"parameter_error">>}, Req}
		end,
	case Ret of
		{ok,{SessionKey,Name,HeadImg,Sex},NewReq} ->
			server_tools:send_to_agent_mng({update_usrinfo,self(),util:to_binary(SessionKey),Name,HeadImg,Sex}),
			{loop, NewReq, undefined, 10000, hibernate};
		{false, {Code,Msg}, NewReq} ->
			JsObj = {obj, [
						   {"code", Code},
						   {"errorMsg", util:to_binary(Msg)}]
					},
			JsStr = rfc4627:encode(JsObj),
			{ok, NewReq2} = cowboy_req:reply(200, [{<<"content-type">>,<<"text/plain">>}], util:to_binary(JsStr), NewReq),
			{shutdown, NewReq2, undefined}
	end.

info({reply, Body}, Req, State) ->
	?log("reply.......update_usrinfo_handler..Body=~p",[Body]),
    {ok, Req2} = cowboy_req:reply(200, [{<<"content-type">>,<<"text/plain">>}], Body, Req),
    {ok, Req2, State};
info(_Msg, Req, State) ->
	?debug("unknown msg,~p",[_Msg]),
    {loop, Req, State, hibernate}.

terminate(_Reason, _Req, _State) ->
	?debug("terminate,~p",[_Reason]),
	ok.


get_input_data(Req) ->
	{Method, Req2} = cowboy_req:method(Req),
	HasBody = cowboy_req:has_body(Req2),
	get_input_data(Method, HasBody, Req2).

get_input_data(<<"POST">>, true, Req2) ->
	Data = cowboy_req:get(buffer,Req2),
%% 	case cowboy_req:body_qs(Req) of
%% 		{ok, PostVals, Req2} ->
 			?log("PostVals.........update usrinfo .....="),
%% 		case PostVals of
%% 				[{Data, true}] ->
					case rfc4627:decode(Data) of
						{ok, {obj, KvList}, _Reminder} ->
							case util:get_values(["sessionId","nickname","headimgurl","sex"], KvList) of
								[SessionKey,Name,HeadImg,Sex] -> {ok, {SessionKey,Name,HeadImg,Sex}, Req2};
								_ -> Req2
							end;
%% 						_ -> Req2
%% 					end;	
%% 				_ -> Req2
%% 			end;
		_ -> Req2
	end;	
get_input_data(_Method, _HasBody, Req) -> Req.
